package practice.unionfind;

import java.util.Arrays;

/**
 * @Description:
 * @Author Ammar
 * @Create 2023/8/26 19:43
 */
public class QuickUnion_rank extends QuickUnion {
    int[] ranks;

    public QuickUnion_rank(int capacity) {
        super(capacity);
        ranks = new int[parent.length];
        Arrays.fill(ranks, 1);
    }

    @Override
    public void union(int v1, int v2) {
        int p1 = find(v1);
        int p2 = find(v2);
        if (p1 == p2) return;
        if (ranks[p1] > ranks[p2]) {
            parent[p2] = p1;
        } else if (ranks[p1] < ranks[p2]) {
            parent[p1] = p2;
        } else {
            parent[p2] = p1;
            ranks[p1]++;
        }
    }
}
